<?php
namespace App\Repos;

use App\Models\Task;
use App\Models\User;
use App\Models\TaskProcess;
use App\Models\TaskService;
use App\Models\TaskDepart;
use App\Models\Client;
use App\Models\ClientUser;

use DB,Log;
use App\Services\Wechat;

class TaskRepo
{
	
    // 创建工单
	public static function save($data)
    {
        $rs['status'] = false;
        DB::beginTransaction();
        try{           
           $services = array_pull($data,'service'); 
           $departs  = array_pull($data,'depart');
           $depart_total_money =  array_sum($departs['total_price']);
           $service_total_money = array_sum($services['service_price']);
           $data['total_money'] = $depart_total_money+$service_total_money;
           // if($data['rate']) {
           //  $data['total_money'] = round($data['total_money']*$data['rate']/100,2);
           // }
           $flag = Task::create($data); 


            foreach ($services['service_type'] as $k => $v) {

                $service['task_id'] = $flag->id;
                $service['service_type'] = $v;
                $service['service_name']  = $services['service_name'][$k];
                $service['service_price'] = $services['service_price'][$k];
                TaskService::create($service);
            }  
            if($departs) {
                foreach ($departs['depart_name'] as $k => $v) {
                    if(empty($v)) continue;
                    $depart['task_id']     = $flag->id;
                    $depart['depart_name']   = $v;
                    $depart['depart_num']    = $departs['depart_num'][$k];
                    $depart['depart_price']  = $departs['depart_price'][$k];
                    $depart['total_price'] = $departs['total_price'][$k];
                    TaskDepart::create($depart);

                    DepartRepo::updateStore($depart);
                    // 库存数量修改
                }     
            }
            
            $process['task_id']   = $flag->id;
            $process['worker_id'] = $data['worker_id'];
            $process['status']    = 1;
            $process['creater']= $data['creater'];
            TaskProcess::create($process);    
            
            if(!$flag) {
                DB::rollBack();
                $rs['msg'] = '添加工单失败';
                return $rs;
            } 
        } catch(\Exception $e) {
            DB::rollBack();
            $rs['msg'] = $e->getMessage();
            return $rs;
        }
        
        DB::commit();
        $rs['status'] = true;
        $rs['data']['task_id'] = $flag->id;
        return $rs;
    }

    public static function update($data,$id)
    {
        return Task::where(['id'=>$id])->update($data);
    }

    public static function refund($data)
    {
        $rs['status'] = false;
        $rs['msg'] = '操作失败';
        $task = Task::find($data['task_id']);
        $task->status = 0;
        $flag = $task->save();

        // process表记录退单信息
        $process['task_id'] = $task->id;
        $process['remark'] = '被退单，退单原因:'.$data['refund_reason'].',操作人:'.$data['username'];
        $process['status'] = 0;
       
        TaskProcess::create($process);

        // 推送消息给提交者
        $msg = $task->toArray();
        $msg['first']      = '工单被退回';
       
        $msg['refund_reason'] = $data['refund_reason'];
           
        $msg['url']     = '';   

        Wechat::sendMsgTpl('refund',$msg);
        if($flag) {
            $rs['status'] = true;
            $rs['msg']    = '操作成功';
        }

        return $rs;
    }

    public static function addService($data)
    {
        $rs['status'] = true;
        DB::beginTransaction();
        try{ 
        $task = Task::find($data['task_id']);
        $task->total_money = $task->total_money+$data['service_price'];
        $task->save();
        TaskService::create($data);
        } catch(\Exception $e) {
            DB::rollBack();
            $rs['status'] = false;
            $rs['msg']    = $e->getMessage();
            return $rs;
        }
        DB::commit();
        return $rs;
    }

    /**
     * 删除服务项
     */
    public static function delService($data)
    {
        $rs['status'] = true;
        DB::beginTransaction();
        try{
            $ts = TaskService::find($data['id']);
            $ts->delete();
            $task = Task::find($data['task_id']);
            $task->total_money = $task->total_money-$ts->service_price;
            $task->save();
        } catch(\Exception $e) {
            DB::rollBack();
            $rs['status'] = false;
            $rs['msg']    = $e->getMessage();
            return $rs;
        }
        DB::commit();
        return $rs;
    }

    /**
     * 删除工单单条配件信息
     */
    public static function delDepart($data)
    {
        $rs['status'] = true;
        DB::beginTransaction();
        try{
            $ts = TaskDepart::find($data['id']);

            $ts->delete();
            $task = Task::find($data['task_id']);
            $task->total_money = $task->total_money-$ts->total_price;
            $task->save();
        } catch(\Exception $e) {
            DB::rollBack();
            $rs['status'] = false;
            $rs['msg']    = $e->getMessage();
            return $rs;
        }
        DB::commit();
        return $rs;
    }

    /**
     * 工单增加单条配件信息
     */
     public static function addDeprt($data)
    {
        $rs['status'] = true;
        DB::beginTransaction();
        try{ 
        $task = Task::find($data['task_id']);
        $task->total_money = $task->total_money+$data['total_price'];
        $task->save();
        TaskDepart::create($data);
        DepartRepo::updateStore($data);
        } catch(\Exception $e) {
            DB::rollBack();
            $rs['status'] = false;
            $rs['msg']    = $e->getMessage();
            return $rs;
        }
        DB::commit();
        return $rs;
    }

    /**
     * 新单推送
     */
    public static function newTaskPush($data)
    {
        // try {
        //     $client = Client::find($data['client_id']);
        //     $msg = $data;
        //     $msg['openid'] = $client->openid;            
        //     $msg['first']  = '您提交的新工单已生成';                 
        //     $msg['remark'] = '点击查看详情。';
        //     $msg['url']    = config('app.url').'/user/task/show/'.$data['id'];
        //     Wechat::sendMsgTpl('baoyang',$msg);
        //     Log::info('新单：推送给用户成功');
              
        // } catch (\Exception $e) {
        //     Log::error('新单推送失败：'.$e->getMessage());
        // }
            
    }

    /**
     * 派工
     */
    public static  function dispatch($data)
    {       
       
        $worker = User::find($data['worker_id']);
        if(empty($worker)) return false;
        $task   = Task::find($data['task_id']);       
        $data['worker_openid'] = $worker->openid;        
        $flag = self::process($data);  

        
        //维修进厂通知 to client
        $msg = $task->toArray(); 
        $msg['car_num'] = $task->car_num;  
        $msg['worker_name']   = $worker->truename;
        $msg['worker_phone']  = $worker->phone;
        $msg['first']  = '进场维修通知';       
        $msg['url']    = config('app.url').'/user/task/show/'.$task->id;
        // $clientUsers = ClientUser::where('client_id',$data['client_id'])->get();

        // foreach ($clientUsers as $key => $cu) {
             

        //     $msg['openid'] = $cu->openid; 
            
        //     Wechat::sendMsgTpl('new_to_client',$msg);
        // }
        

        // 推送消息
        $msg2 = $msg;
        $msg2['first']  = '有新的工单，请及时处理！';     
        $msg2['openid'] = $worker->openid;       
        Wechat::sendMsgTpl('dispatch_to_client&worker',$msg2);

        $task->status = 50;
        $flag = $task->save();
        if($flag) return true;
        return false;
    }

    private static function process($data)
    {        
        $data = array_only($data,['task_id','worker_id','remark']);
        $data['status'] =  50;  
        TaskProcess::create($data);

        $updateData = array_only($data,['worker_id','status']);       
        $flag = Task::where('id',$data['task_id'])->update($updateData);
        return $flag;
    }

    public static function complete($data)
    {
        $rs['status'] = true;
        DB::beginTransaction();
        try{
            $task   = Task::find($data['task_id']);
            $task->status = 100;
            $flag = $task->save();
            $data['worker_id'] = $task->worker_id;
            $data['task_id']   = $task->id;
            $data['status']    =  1000;  
            TaskProcess::create($data);
        } catch(\Exception $e) {
            DB::rollBack();
            $rs['status'] = false;
            $rs['msg'] = $e->getMessage();
            return $rs;
        }
        DB::commit();
        return $rs;
    }

    public static function changeStatus($data)
    {
        
        // $rs['status'] = true;
        // $task = Task::find($data['id']);
        // $task->status = $data['status'];
        // $task->save();


        // $clientUsers = ClientUser::where('client_id',$task->client_id)->get();
        // $msg['car_num']       = $task->car_num?$task->car_num:object_get($task,'car.car_num'); 
        // $msg['maintain_name'] = object_get($task,'maintain.name');
        // $msg['status_txt']    = $task->status_txt;
        // $msg['url']    = config('app.url').'/user/task/show/'.$task->id;
        // foreach ($clientUsers as $key => $cu) {   

        //    // 推送消息          
        //     $msg['openid'] = $cu->openid;       
        //     Wechat::sendMsgTpl('process',$msg);
        // }

        // return $rs;
        
    }


    

	
	
}